package cn.lzwei.bilimall.product.service.impl;

import cn.lzwei.bilimall.product.dao.AttrAttrgroupRelationDao;
import cn.lzwei.bilimall.product.dao.AttrGroupDao;
import cn.lzwei.bilimall.product.dao.CategoryDao;
import cn.lzwei.bilimall.product.entity.AttrAttrgroupRelationEntity;
import cn.lzwei.bilimall.product.entity.AttrGroupEntity;
import cn.lzwei.bilimall.product.entity.CategoryEntity;
import cn.lzwei.bilimall.product.service.AttrAttrgroupRelationService;
import cn.lzwei.bilimall.product.service.AttrGroupService;
import cn.lzwei.bilimall.product.service.CategoryService;
import cn.lzwei.bilimall.product.vo.AttrRespVo;
import cn.lzwei.bilimall.product.vo.AttrVo;
import cn.lzwei.common.constant.ProductConstant;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lzwei.common.utils.PageUtils;
import cn.lzwei.common.utils.Query;

import cn.lzwei.bilimall.product.dao.AttrDao;
import cn.lzwei.bilimall.product.entity.AttrEntity;
import cn.lzwei.bilimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Resource
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Resource
    CategoryDao categoryDao;
    @Resource
    AttrGroupDao attrGroupDao;
    @Resource
    CategoryService categoryService;
    @Resource
    AttrGroupService attrGroupService;
    @Resource
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询分组可以新增关联的属性
     */
    @Override
    public PageUtils noAttrGroupRelation(Map<String, Object> params, Long attrgroupId) {
        //1.获得分类id
        AttrGroupEntity attrGroup = attrGroupService.getById(attrgroupId);
        Long catelogId = attrGroup.getCatelogId();
        //3.获得分类下的所有属性组id
        List<AttrGroupEntity> groupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groupEntities.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
        //4.获得所有已于属性组关联的属性id
        QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();
        if (groupIds!=null && groupIds.size()>0){
            relationWrapper.in("attr_group_id", groupIds);
        }
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(relationWrapper);
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        //5.获得当前分类下 剔除这些属性、销售属性 后剩下的属性
        QueryWrapper<AttrEntity> attrWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());
        //模糊查询
        String key = (String) params.get("key");
        if(!StringUtils.isNullOrEmpty(key)){
            attrWrapper.and(item->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        if (attrIds!=null && attrIds.size()>0){
            attrWrapper.notIn("attr_id", attrIds);
        }
        IPage<AttrEntity> page=attrService.page(
                new Query<AttrEntity>().getPage(params),
                attrWrapper
        );
        return new PageUtils(page);
    }
    /**
     * 查询分组已经关联的属性
     */
    @Override
    public List<AttrEntity> attrGroupRelation(Long attrgroupId) {
        //1.在关联表中查出所有属性id
        List<AttrAttrgroupRelationEntity> entityList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entityList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //非空判断
        if(attrIds==null || attrIds.size()==0) return null;
        //2.利用属性id查询出所有属性
        Collection<AttrEntity> attrEntities = attrService.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    /**
     * 保存：区分销售属性再同步属性属性分组表
     */
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //1.保存属性表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        Integer attrType = attr.getAttrType();
        //只有规格参数才有属性分组
        if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
            //2.保存属性属性分组表
            Long attrGroupId = attr.getAttrGroupId();
            if (attrGroupId!=null){
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    /**
     * 查询：分类、模糊查询（返回包括分类名、分组名）
     */
    @Override
    public PageUtils queryBaseAttr(Map<String, Object> params, Long categoryId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type","base".equalsIgnoreCase(type)?1:0);
        //1.模糊查询
        String key = (String) params.get("key");
        if(!StringUtils.isNullOrEmpty(key)){
            queryWrapper.and(item->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        //2.分类查询
        if(!categoryId.equals(0l)){
            queryWrapper.eq("catelog_id",categoryId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVoList = records.stream().map(item -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item,attrRespVo);
            //3.分类名：查询分类表
            CategoryEntity category = categoryDao.selectById(item.getCatelogId());
            if(category!=null){
                attrRespVo.setCatelogName(category.getName());
            }
            Integer attrType = item.getAttrType();
            //只有规格参数才有属性分组
            if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
                //4.分组名：需要联表
                AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (attrAttrgroupRelation != null){
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                    if(attrGroupEntity!=null){
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    /**
     * 信息：修改时信息回显。区分销售属性、规格参数
     */
    @Override
    public AttrRespVo attrInfo(Long attrId) {
        //1.基本信息
        AttrRespVo attrRespVo=new AttrRespVo();
        AttrEntity attr = this.getById(attrId);
        BeanUtils.copyProperties(attr,attrRespVo);
        Integer attrType = attr.getAttrType();
        //只有规格参数才有属性分组
        if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
            //2.分组信息
            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (attrAttrgroupRelation != null){
                attrRespVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //3.分类名
        CategoryEntity category = categoryDao.selectById(attr.getCatelogId());
        if(category!=null){
            attrRespVo.setCatelogName(category.getName());
        }
        //4.分类路径
        attrRespVo.setCatelogPath(categoryService.findCatelogPath(attr.getCatelogId()));

        return attrRespVo;
    }

    /**
     * 修改：规格参数才需同步属性属性分组表。
     */
    @Override
    @Transactional
    public void updateAttr(AttrVo attrVo) {
        //1.修改基本信息
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        this.updateById(attr);
        Integer attrType = attr.getAttrType();
        //只有规格参数才有属性分组
        if(attrType== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrId(attrVo.getAttrId());
            attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
            if(count>0){
                //2.修改
                attrAttrgroupRelationDao.update(attrAttrgroupRelation,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrVo.getAttrId()));
            }else{
                //3.新增
                attrAttrgroupRelationDao.insert(attrAttrgroupRelation);
            }
        }
    }

}